<?php

/*
 * Copyright 2018 zhuo bing.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace backend\components\widgets\mapbaidu;

use yii\base\Widget;
use Yii;

/**
 * Description 百度地图小部件
 *
 * @author zhuo bing
 *     
 * <?= MapBaiduWidget::widget([
  'lat'=>'26.516855',
  'lng' => '106.73805',
  'defAddress' => '贵阳',    //默认贵阳
  ]); ?>
 */
class MapBaiduWidget extends Widget {

    public $id;
    public $lat;
    public $lng;
    public $latlng = null;
    public $defAddress;
    protected $name;
    public $model;

    public function init() {
        $this->name = explode('\\', get_class($this->model));
        $this->name = $this->name[count($this->name) - 1];
        $this->id = $this->id ? $this->id : 'map';
        if ($this->lat and $this->lng) {
            $this->latlng = $this->lat . ',' . $this->lng;
        }
    }

    public function run() {
        $view = $this->getView();
        parent::run();
        MapBaiduAsset::register($view);
        echo <<<html
        <div class="form-group">
            <label class="col-lg-2 control-label">地图</label>
            <div class="col-lg-7">
                <div class="input-group">
                    <input  type="text" class="form-control" id="{$this->id}_search" name='addressSearch' placeholder="地址搜索" />
                    <span class="input-group-btn">
                        <button class="btn btn-default {$this->id}_search_bn" type="button">搜索!</button>
                    </span>
                </div>        
                <div id="{$this->id}" class="map_container"></div>
                <input type="hidden" name="{$this->name}[{$this->id}_lat]" class="{$this->id}_lat" value="{$this->lat}"/>     
                <input type="hidden" name="{$this->name}[{$this->id}_lng]" class="{$this->id}_lng" value="{$this->lng}"/>  
            </div>
        </div>        
html;

        $this->renderJs($view);
    }

    protected function renderJs($view) {
        $js = <<<js
                map_init('{$this->id}','{$this->latlng}','{$this->defAddress}');                     
js;
        $view->registerJs($js);
    }

}
